<template>
  <div>
    <!-- 面包屑导航 -->
    <Breadcrumb menu="用户管理" submenu="用户列表" />
    <el-card>
      <!-- 顶部搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入用户名"
            v-model.trim="queryInfo.query"
            class="input-with-select"
            @clear="getUserList"
            @keyup.enter.native="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table
        :data="userList"
        style="width: 100%"
        border
        v-loading="showLoading"
      >
        <el-table-column prop="id" label="id" width="50"> </el-table-column>
        <el-table-column label="账号" width="100">
          <template v-slot="{ row }">
            <el-input v-if="row._edit" v-model="row.username" :disabled="true">
            </el-input>
            <span v-else>{{ row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号">
          <template v-slot="{ row }">
            <el-input v-if="row._edit" v-model="row._mobile"> </el-input>
            <span v-else>{{ row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="200px">
          <template v-slot="{ row }">
            <el-input v-if="row._edit" v-model="row._email"> </el-input>
            <span v-else>{{ row.email }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template v-slot="{ row }">{{
            row.create_time | formatDate
          }}</template>
        </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态" width="80">
          <template v-slot="{ row }">
            <el-switch v-model="row.mg_state" @change="changeStatus(row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240px">
          <template v-slot="{ row }">
            <EditButton
              style="margin-right: 10px"
              v-if="row._edit"
              @cancel="cancelEditUserInfo(row)"
              @complete="saveEditUserInfo(row)"
            />
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              round
              v-else
              @click="row._edit = true"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              round
              @click="deleteById(row)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                round
                @click="showSetRoleDialog(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部分页栏目 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 用户添加对话框 -->
    <el-dialog
      title="添加用户"
      @closed="addDialogClosed"
      :visible.sync="addDialogVisible"
      width="30%"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model.trim="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="addForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model.trim="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="30%"
      @close="currUser = {}"
    >
      <p>
        当前用户：<el-tag>{{ currUser.username }}</el-tag>
      </p>
      <p>
        当前角色：<el-tag>{{ currUser.role_name }}</el-tag>
      </p>
      <p>
        分配新角色：<el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    //自定邮箱校验规则
    var checkEmail = (rule, value, callback) => {
      if (this.checkEmail(value)) {
        callback();
      } else {
        callback(new Error("请输入合法的邮箱"));
      }
    };
    //自定义手机号校验规则
    var checkMobile = (rule, value, callback) => {
      if (this.checkMobile(value)) {
        callback();
      } else {
        callback(new Error("请输入合法的手机号"));
      }
    };
    return {
      //用户列表查询参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      //正在编辑的id
      editId: -1,
      userList: [],
      total: 0,
      //控制加载框的显示
      showLoading: false,
      //控制添加用户对话框的显示
      addDialogVisible: false,
      //控制分配角色对话框显示和隐藏
      setRoleDialogVisible: false,
      //要进行分配角色的用户
      currUser: {},
      //角色列表
      roleList: [],
      //已选中的角色id
      selectRoleId: "",
      //添加用户表单对象
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },

      //添加用户表达验证对象
      addFormRules: {
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },

  methods: {
    checkMobile(val) {
      var reg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
      return reg.test(val);
    },
    checkEmail(val) {
      //判断这个文本框中输入的是不是邮箱
      var reg = /^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/;
      return reg.test(val);
    },
    //获取用户列表数据
    async getUserList() {
      this.showLoading = true;
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      this.showLoading = false;
      res.data.users.forEach((el) => {
        el._email = el.email;
        el._mobile = el.mobile;
        el._edit = false;
      });
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    //多少条每页显示的回调
    handleSizeChange(pageSize) {
      this.queryInfo.pagesize = pageSize;
      this.getUserList();
    },
    //选中第几页的回调
    handleCurrentChange(pageNum) {
      this.queryInfo.pagenum = pageNum;
      this.getUserList();
    },
    //改变用户状态
    async changeStatus(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      this.$message.success("修改用户状态成功！");
    },
    //dialog对话框关闭时候的回调
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //添加用户数据
    addUser() {
      this.$refs.addFormRef.validate((val) => {
        if (!val) return;
        this.$http.post("users", this.addForm);
        this.addDialogVisible = false;
        this.$message.success("添加用户成功");
        this.getUserList();
      });
    },
    //发送更新用户信息请求
    async sendUpdateUserInfo(userInfo) {
      const { data: res } = await this.$http.put(`users/${userInfo.id}`, {
        email: userInfo._email,
        mobile: userInfo._mobile,
      });
      this.$message.success("用户信息更新成功");
      userInfo.email = userInfo._email;
      userInfo.mobile = userInfo._mobile;
    },
    //取消编辑用户
    cancelEditUserInfo(userInfo) {
      userInfo._email = userInfo.email;
      userInfo._mobile = userInfo.mobile;
      userInfo._edit = false;
    },
    //保存编辑用户信息
    saveEditUserInfo(userInfo) {
      if (!userInfo._email || !this.checkEmail(userInfo._email)) {
        this.$message.error("请输入合法的邮箱");
        return;
      }
      if (!userInfo._mobile || !this.checkMobile(userInfo._mobile)) {
        this.$message.error("请输入合法的手机号");
        return;
      }
      this.sendUpdateUserInfo(userInfo);
      userInfo._edit = false;
    },
    //通过id删除用户信息
    deleteById(userInfo) {
      this.$confirm(
        `此操作将永久删除 ${userInfo.username}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          await this.$http.delete(`users/${userInfo.id}`);
          this.$message.success("删除成功");
          this.getUserList();
        })
        .catch((error) => error);
    },
    //显示分配角色对话框
    async showSetRoleDialog(userInfo) {
      this.currUser = userInfo;
      const { data: res } = await this.$http.get("roles");
      this.roleList = res.data;
      this.setRoleDialogVisible = true;
    },
    //给用户分配新角色
    async setRole() {
      this.setRoleDialogVisible = false;
      await this.$http.put(`users/${this.currUser.id}/role`, {
        rid: this.selectRoleId,
      });
      this.$message.success(`给用户 ${this.currUser.username} 分配新角色成功`);
      this.getUserList();
    },
  },
  created() {
    this.getUserList();
  },
};
</script>

<style lang="less" scoped>
.el-table .el-input /deep/ input {
  height: 25px;
}
</style>

